package io.renren.modules.calculator.controller;

import io.renren.modules.calculator.dto.CodeRequest;
import io.renren.modules.calculator.dto.ExecutionResult;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/python")
public class PythonController {

    // 配置Python路径，默认使用"python3"，可根据实际情况修改
    private static final String PYTHON_EXECUTABLE = "C:\\Users\\Baisy\\anaconda3\\python.exe";
    // 执行超时时间(秒)
    private static final long EXECUTION_TIMEOUT = 30;

    @PostMapping("/execute")
    public ExecutionResult executePython(@RequestBody CodeRequest request) {
        System.out.println("1");
        if (request.getCode() == null || request.getCode().trim().isEmpty()) {
            return new ExecutionResult("", false, "Python代码不能为空");
        }

        Process process = null;
        try {
            // 创建临时Python文件
            File tempScript = createTempPythonFile(request.getCode());

            ProcessBuilder pb = new ProcessBuilder(PYTHON_EXECUTABLE, tempScript.getAbsolutePath());
            pb.redirectErrorStream(true); // 合并标准错误和标准输出

            process = pb.start();

            // 读取输出
            StringBuilder output = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    output.append(line).append("\n");
                }
            }

            // 等待进程完成
            boolean finished = process.waitFor(EXECUTION_TIMEOUT, TimeUnit.SECONDS);
            if (!finished) {
                process.destroyForcibly();
                return new ExecutionResult("", false, "执行超时(超过" + EXECUTION_TIMEOUT + "秒)");
            }

            int exitCode = process.exitValue();
            if (exitCode != 0) {
                return new ExecutionResult(output.toString(), false, "Python执行失败(退出码: " + exitCode + ")");
            }

            return new ExecutionResult(output.toString(), true, null);
        } catch (Exception e) {
            return new ExecutionResult("", false, "系统错误: " + e.getMessage());
        } finally {
            if (process != null && process.isAlive()) {
                process.destroyForcibly();
            }
        }
    }

    private File createTempPythonFile(String code) throws IOException {
        File tempScript = File.createTempFile("script", ".py");

        // 确保文件在程序退出时删除
        tempScript.deleteOnExit();

        try (FileWriter writer = new FileWriter(tempScript)) {
            // 添加Python环境检查
            writer.write("import sys\n");
            writer.write("print(f\"Python版本: {sys.version}\")\n");
            writer.write("print(\"---------------------------------\")\n");
            writer.write(code);
        }

        return tempScript;
    }
    @GetMapping("/checkPython")
    public String checkPythonEnvironment() {
        try {
            Process process = new ProcessBuilder(PYTHON_EXECUTABLE, "--version").start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String version = reader.readLine();
            return "Python环境正常检测到: " + version;
        } catch (Exception e) {
            return "Python环境检测失败: " + e.getMessage();
        }
    }
}
